﻿using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.PM;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace FarmSmartSleep.Organ.API.Application.ProductionManagement.MotherGivingBirthFile
{
    /// <summary>
    /// 种母分娩
    /// </summary>
    public class MotherGivingBirthListHandler : IRequestHandler<MotherGivingBirthListCommon, ResultPage<List<MotherGivingBirthListDto>>>
    {

        private readonly IBaseRepository<MotherGivingBirth> motherGivingBirthRep;
        private readonly IBaseRepository<SleepInfor> _sleepinforRep;
        private readonly IBaseRepository<Cottages> cottagesRep;
        private readonly IBaseRepository<Fields> fieldsRep;

        public MotherGivingBirthListHandler(IBaseRepository<MotherGivingBirth> motherGivingBirthRep, IBaseRepository<SleepInfor> sleepinforRep, IBaseRepository<Cottages> cottagesRep, IBaseRepository<Fields> fieldsRep)
        {
            this.motherGivingBirthRep = motherGivingBirthRep;
            _sleepinforRep = sleepinforRep;
            this.cottagesRep = cottagesRep;
            this.fieldsRep = fieldsRep;
        }

        public async Task<ResultPage<List<MotherGivingBirthListDto>>> Handle(MotherGivingBirthListCommon request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<List<MotherGivingBirthListDto>>() { Code = (int)CodeEnum.search };

            try
            {
                var motherGivingBirth = motherGivingBirthRep.GetAll().Where(x => x.Deletes == false);
                var sleepinfor = _sleepinforRep.GetAll();
                var cottages = cottagesRep.GetAll();
                var fields = fieldsRep.GetAll();
                var listQuery = (from s in sleepinfor
                                 join m in motherGivingBirth
                                 on s.SleepInforId equals m.EweID
                                 join c in cottages on m.CurrentBarn equals c.CottagesId
                                 join f in fields on m.CurrentPen equals f.FieIdId
                                 join c1 in cottages on m.TransferBarn equals c1.CottagesId
                                 join f1 in fields on m.TransferPen equals f1.FieIdId
                                 select new MotherGivingBirthListDto
                                 {
                                     MotherGivingBirthId = m.MotherGivingBirthId,
                                     Leader = m.Leader,
                                     MotherData = m.MotherData,
                                     EweName = s.EarNumber,
                                     EweID = s.SleepInforId,
                                     PregnancyDays = m.PregnancyDays,
                                     DeliveryEase = m.DeliveryEase,
                                     BatchNumber = m.BatchNumber,
                                     MaternalBehavior = m.MaternalBehavior,
                                     Lactation = m.Lactation,
                                     Mastitis = m.Mastitis,
                                     LitterID = m.LitterID,
                                     HealthyLambsCount = m.HealthyLambsCount,
                                     WeakLambsCount = m.WeakLambsCount,
                                     DeformedLambsCount = m.DeformedLambsCount,
                                     StillbornLambsCount = m.StillbornLambsCount,
                                     MummifiedLambsCount = m.MummifiedLambsCount,
                                     MalformedFetusCount = m.MalformedFetusCount,
                                     LiveLambs = m.LiveLambs,
                                     LitterTotalWeight = m.LitterTotalWeight,
                                     Gender = m.Gender,
                                     CurrentBarn = c.CottageName,
                                     CurrentBarnId = c.CottagesId,
                                     CurrentPen = f.FieIdName,
                                     TransferBarn = c1.CottageName,
                                     TransferBarnId = c1.CottagesId,
                                     TransferPen = f1.FieIdName,
                                     Notes = m.Notes,
                                     DocumentNo = m.DocumentNo,
                                     SerialNo = m.SerialNo,
                                     CreateId = m.CreateId,
                                     CreateTime = m.CreateTime,
                                     UpdateId = m.UpdateId,
                                     UpdateTime = m.UpdateTime,
                                     DeleteId = m.DeleteId,
                                     Deletes = m.Deletes,
                                     DeleteTime = m.DeleteTime,
                                     ExamId = m.ExamId,
                                     ExamTime = m.ExamTime
                                 }).AsQueryable();
                if (!string.IsNullOrEmpty(request.Leader))
                {
                    listQuery = listQuery.Where(x => x.Leader.Contains(request.Leader));
                }
                if (request.CurrentBarn != 0)
                {
                    listQuery = listQuery.Where(x => x.CurrentBarnId == request.CurrentBarn);
                }
                if (request.TransferBarn != 0)
                {
                    listQuery = listQuery.Where(x => x.TransferBarnId == request.TransferBarn);
                }
                if (request.LitterID != 0)
                {
                    listQuery = listQuery.Where(x => x.LitterID == request.LitterID);
                }
                if (request.MinDate != null)
                {
                    listQuery = listQuery.Where(x => x.MotherData >= request.MinDate);
                }
                if (request.MaxDate != null)
                {
                    listQuery = listQuery.Where(x => x.MotherData <= request.MaxDate);
                }
                if (request.EweID != 0)
                {
                    listQuery = listQuery.Where(x => x.EweID == request.EweID);
                }
                if (listQuery == null || !listQuery.Any())
                {
                    result.Messege = "暂无数据";
                    return result;
                }
                //仅在筛选后转换为列表
                var list = listQuery.ToList();
                result.totalCount = list.Count();
                result.totalPage = (int)Math.Ceiling(result.totalCount / (double)request.PageSize);
                list = list.OrderBy(c => c.MotherGivingBirthId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Code = (int)CodeEnum.success;
                result.Item = list;
                result.Messege = "查询成功";


            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
